<?php
namespace app\api\model;

class Product extends BaseModel{
    //pivot字段表示多对多关系表中的字段，自动添加的
    protected $hidden = ['delete_time', 'main_img_id', 'pivot', 'from', 'category_id', 
                        'create_time', 'update_time'];

    protected function getMainImgUrlAttr($value, $data){
        return $this->prefixImgUrl($value, $data);
    }

    public function imgs(){
        return $this->hasMany('product_image', 'product_id', 'id');
    }

    public function properties(){
        return $this->hasMany('product_property', 'product_id', 'id');
    }

    public static function getMostRecent($count){
        $products = self::limit($count)
                    ->order('create_time desc')
                    ->select();
        return $products;
    }


    public static function getProdustByCategory($categoryID){
        $products = self::where('category_id', '=', $categoryID)
                    ->select();
        return $products;
    }

    public static function getProductDetail($id){
        $product = self::with([
                        'imgs' => function($query){
                            $query->with(['imgUrl'])
                                ->order('order', 'asc');
                        }
                    ])
                    ->with(['properties'])
                    ->find($id);
        return $product;
    }
}

?>